package service

import (
	"gin-worked/app/system/model"
	"strconv"
	"strings"
)

// MenuRoleList 角色菜单列表
func MenuRoleList(roleId string) Res {

	roleIds, _ := strconv.Atoi(roleId)

	data := &model.MenuRole{
		RoleId: roleIds,
	}

	field := []string{"role_id", "menu_id"} //查询字段

	list, err := model.MenuRoleList(data, field)
	if err != nil {
		return Res{0, err.Error(), ""}
	}

	return Res{1, "success", list}
}

// MenuRoleSet 设置角色的菜单
func MenuRoleSet(RoleId string, MenuId string) Res {
	roleIds, _ := strconv.Atoi(RoleId)

	where := &model.MenuRole{}

	where.RoleId = roleIds
	field := []string{"role_id", "menu_id"} //查询字段
	_, err := model.MenuRoleInfo(where, field)

	if err == nil {
		_ = model.MenuRoleDel(where)
	}

	MenuIds := strings.Split(MenuId, ",") // 使用Split函数按照逗号分割字符串

	var menuRole []model.MenuRole

	for _, value := range MenuIds {
		values, _ := strconv.Atoi(value)
		menuRole = append(menuRole, model.MenuRole{RoleId: roleIds, MenuId: values})
	}

	err1 := model.MenuRoleAddAll(menuRole)

	if err1 != nil {
		return Res{0, err1.Error(), ""}
	}

	return Res{1, "success", ""}

}
